#include "memfd_share.h"
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include "gperftools/profiler.h"

#define IMG_BUF_SIZE  1257924
#define SEND_BUF_SIZE 3 * 1024 * 1024

typedef struct AlgDataHeader
{
    unsigned char dataType;
    unsigned char res[3];
    int dataLen;
} algDataHeader_t;

/*图像数据头*/
typedef struct AlgPictureDataHead
{
    unsigned int dwWidth;    //宽度
    unsigned int dwHeigt;    //高度
    unsigned int dwChan;     //通道号
    unsigned int dwSize;     //图像大小
    unsigned int dwOrder;    //序号
    unsigned int dwExposure; //曝光时间,单位us
    unsigned int dwTimeSec;  //采集时间,s
    unsigned int dwTimeNs;   //采集时间,ns
    char szId[64];
    char szName[32];         //相机名称
    unsigned char byType;    //类型
    unsigned char byFormt;   //格式
    unsigned int devID;      //设备ID
    unsigned char camID;     //相机ID
    unsigned char byRes[12]; //预留
    //unsigned char data[0];
} algPictureDataHead_t;


void handleALgData(unsigned char *pData, unsigned int dwDataLen, void *pUserData)
{
    algDataHeader_t *pAlgDataHeader = NULL;
    algPictureDataHead_t *pImgHeader = NULL;
    unsigned char *pImgData = NULL;
    timespec timeStamp;
    int tm1, tm2;

    if (pData == NULL || dwDataLen == 0)
    {
        printf("[%s:%d] invalid parameters!.\n", __func__, __LINE__);
        return;
    }

    pAlgDataHeader = (algDataHeader_t *)pData;

    switch (pAlgDataHeader->dataType)
    {
    case 1:
        pImgHeader = (algPictureDataHead_t *)(pAlgDataHeader + 1);
        pImgData = (unsigned char *)(pImgHeader + 1);
        clock_gettime(CLOCK_REALTIME, &timeStamp);

        printf("got devID:%d ,size:%d, timestamp:%010u.%09u, now:%010lu.%09lu \n", pImgHeader->devID, pImgHeader->dwSize, 
        pImgHeader->dwTimeSec, pImgHeader->dwTimeNs, timeStamp.tv_sec, timeStamp.tv_nsec);
        tm1 = (pImgHeader->dwTimeSec % 100) * 1000 + pImgHeader->dwTimeNs / 1000000;
        tm2 = (timeStamp.tv_sec % 100) * 1000 + timeStamp.tv_nsec / 1000000;
        printf("[%s:%d] -------------Total sub data cost:%dms------------ \n\n", __func__, __LINE__, (tm2 - tm1));
        break;
    default:
        break;
    }

    return;
}

int main(int argc, const char **argv)
{
    //ProfilerStart("test_gperftools.prof");

    char topic[128] = "hello";  

    /*订阅传感器原始数据*/
    int iRet;
    iRet = share::MEMFD_Init();
    iRet = share::MEMFD_Subscriber(topic, handleALgData, NULL);
    if (iRet != 0)
    {
        printf("[%s:%d] subscriber failed.\n", __func__, __LINE__);
        return -1;
    }

    //ProfilerStop();


    while (1)
    {
        sleep(1);
        /* code */
    }

    //share::MEMFD_Release();
    return 0;
}